//
//  TogetherDateArrangerCell.m
//  Together_iOS
//
//  Created by applex on 14-2-28.
//  Copyright (c) 2014年 QIU Shuang. All rights reserved.
//

#import "TogetherDateArrangerCell.h"
#import "TogetherRatingView.h"
#import "Plan.h"
#import <SSToolkit/SSCategories.h>
#import <SSToolkit/SSToolkit.h>
#import "Stop.h"
#import "TogetherUtils.h"

@interface TogetherDateArrangerCell ()

// background image
@property (strong, nonatomic) UIImageView *district;
@property (strong, nonatomic) UIImageView *body;

// labels
@property (strong, nonatomic) UILabel *beginningTime;
@property (strong, nonatomic) UILabel *region;
@property (strong, nonatomic) UILabel *shop;
@property (strong, nonatomic) UILabel *cost;
@property (nonatomic, strong) UIButton *reservationButton;

// accessories
@property (strong, nonatomic) TogetherRatingView *rating;

@property (strong, nonatomic) UIImageView *more;

@end

@implementation TogetherDateArrangerCell

@synthesize district = _district;
@synthesize body     = _body;
@synthesize beginningTime = _beginningTime;
@synthesize region = _region;
@synthesize shop   = _shop;
@synthesize cost = _cost;
@synthesize rating  = _rating;
@synthesize more = _more;


- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier withData:(Stop *)event
{
    self = [self initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        _event = event;
    }
    return self;
}


- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        UIColor *bColor = [[UIColor alloc] initWithRed:0.965 green:0.957 blue:0.918 alpha:1];
        UIView *backgroundView = [[UIView alloc] initWithFrame:self.frame];
        backgroundView.backgroundColor = bColor;
        self.backgroundView = backgroundView;
        [self.contentView setBackgroundColor:bColor];
        
        // district background
        self.district = [[UIImageView alloc] init];
        self.district.frame = CGRectMake(0, 0, 82, 77);
        _district.backgroundColor = [UIColor clearColor];
        [self.contentView addSubview:self.district];
        
        // start time
        self.body = [[UIImageView alloc] init];
        self.body.frame = CGRectMake(78, 0, 224, 77);
        [self.contentView addSubview:self.body];

        // event region
        self.beginningTime = [[UILabel alloc] init];
        self.beginningTime.frame = CGRectMake(7, 11, 50, 18);
        self.beginningTime.textColor = [UIColor whiteColor];
        self.beginningTime.font = [UIFont systemFontOfSize:18.];
        [self.contentView addSubview:self.beginningTime];

        // shop information
        self.region = [[UILabel alloc] init];
        self.region.frame = CGRectMake(7, 47, 65, 14);
        self.region.textColor = [UIColor whiteColor];
        self.region.font = [UIFont systemFontOfSize:14.];
        [self.contentView addSubview:self.region];

        self.shop = [[UILabel alloc] init];
        self.shop.frame = CGRectMake(82, 15, 193, 18);
        self.shop.textColor = [UIColor whiteColor];
        self.shop.font = [UIFont systemFontOfSize:14.];
        [self.contentView addSubview:self.shop];

        self.rating = [[TogetherRatingView alloc] initWithFrame:CGRectMake(82, 56, 40, 8)];
        [self.contentView addSubview:self.rating];
        
        self.rating = [[TogetherRatingView alloc] initWithFrame:CGRectMake(82, 56, 40, 8)];
        [self.contentView addSubview:self.rating];

        self.cost = [[UILabel alloc] init];
        self.cost.frame = CGRectMake(82, 35, 180, 15);
        self.cost.textColor = [UIColor whiteColor];
        self.cost.font = [UIFont systemFontOfSize:14.];
        [self.contentView addSubview:self.cost];

        self.more = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_more.png"]];
        self.more.frame = CGRectMake(284, 35, 9, 15);
        [self.contentView addSubview:self.more];
        
        UIView *selectedBackgroundView = [[UIView alloc] initWithFrame:self.frame];
        backgroundView.backgroundColor = [UIColor clearColor];
        self.selectedBackgroundView = selectedBackgroundView;
        _shouldDrag = YES;
        
        _reservationButton = [[UIButton alloc] initWithFrame:CGRectMake(265., 0., self.frame.size.width - 265., 75.)];
        _reservationButton.backgroundColor = [UIColor clearColor];
        [_reservationButton addTarget:self action:@selector(reserve:) forControlEvents:UIControlEventTouchUpInside];
        [self.contentView addSubview:_reservationButton];

    }
    return self;
    
}


- (void)setEvent:(Stop *)event {
    _event = event;
    NSArray *typeToBackground = [NSArray arrayWithObjects:@"food", @"enter", @"movie", nil];
    if (self) {
        NSString *districtSb = [NSString stringWithFormat:@"bg_%@_district.png", [typeToBackground objectAtIndex:MAX([event.type integerValue] - 1, 0)]];
        NSString *streetSb = [NSString stringWithFormat:@"bg_%@_street.png", [typeToBackground objectAtIndex:MAX([event.type integerValue] - 1, 0)]];
        
        // district background
        self.district.image = [UIImage imageNamed:districtSb];

        self.body.image = [UIImage imageNamed:streetSb];
        
        // start time
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"HH:mm"];
        self.beginningTime.text = [dateFormatter stringFromDate:event.startTime];
        
        // event region
        NSArray *listItems = [event.regions componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"[]\" ,"]];
        NSEnumerator *enumerator = [listItems reverseObjectEnumerator];
        id object;
        while (object = [enumerator nextObject]) {
            NSString *tmp = (NSString *)object;
            if ([tmp length]) {
                break;
            }
        }
        self.region.text = object;
        
        // shop information
        self.shop.text = event.name;
        
        self.rating.rating = event.product_score;
        
        NSString *categories = event.categories;
//        NSArray *ar = [TogetherUtils arrayOrNSDictionaryFromJsonString:[categories dataUsingEncoding:NSUTF8StringEncoding]];
        self.cost.text = [NSString stringWithFormat:@"%@", categories];
        
    }
}


-(UIImageView*)checkmarkGreyImageView {
    if (!_checkmarkGreyImageView) {
        _checkmarkGreyImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetHeight(self.frame) - 20., CGRectGetHeight(self.frame))];
        [_checkmarkGreyImageView setImage:[UIImage imageNamed:@"CheckmarkGrey"]];
        [_checkmarkGreyImageView setContentMode:UIViewContentModeCenter];
        [self.backView addSubview:_checkmarkGreyImageView];
    }
    return _checkmarkGreyImageView;
}


-(UIImageView*)checkmarkGreenImageView {
    if (!_checkmarkGreenImageView) {
        _checkmarkGreenImageView = [[UIImageView alloc] initWithFrame:self.checkmarkGreyImageView.bounds];
        [_checkmarkGreenImageView setImage:[UIImage imageNamed:@"CheckmarkGreen"]];
        [_checkmarkGreenImageView setContentMode:UIViewContentModeCenter];
        [self.checkmarkGreyImageView addSubview:_checkmarkGreenImageView];
    }
    return _checkmarkGreenImageView;
}


-(UIImageView*)checkmarkProfileImageView {
    if (!_checkmarkProfileImageView) {
        _checkmarkProfileImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"CheckmarkProfileImage"]];
        [_checkmarkProfileImageView setFrame:CGRectMake(30 - 10 - CGRectGetWidth(_checkmarkProfileImageView.frame), 30 - 10 - CGRectGetHeight(_checkmarkProfileImageView.frame), CGRectGetWidth(_checkmarkProfileImageView.frame), CGRectGetHeight(_checkmarkProfileImageView.frame))];
    }
    return _checkmarkProfileImageView;
}


-(UIImageView*)deleteGreyImageView {
    if (!_deleteGreyImageView) {
        _deleteGreyImageView = [[UIImageView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.contentView.frame), 0, CGRectGetHeight(self.frame) - 20., CGRectGetHeight(self.frame))];
        [_deleteGreyImageView setImage:[UIImage imageNamed:@"DeleteGrey"]];
        [_deleteGreyImageView setContentMode:UIViewContentModeCenter];
        [self.backView addSubview:_deleteGreyImageView];
    }
    return _deleteGreyImageView;
}


-(UIImageView*)deleteRedImageView {
    if (!_deleteRedImageView) {
        _deleteRedImageView = [[UIImageView alloc] initWithFrame:self.deleteGreyImageView.bounds];
        [_deleteRedImageView setImage:[UIImage imageNamed:@"DeleteRed"]];
        [_deleteRedImageView setContentMode:UIViewContentModeCenter];
        [self.deleteGreyImageView addSubview:_deleteRedImageView];
    }
    return _deleteRedImageView;
}


-(void)prepareForReuse {
	[super prepareForReuse];
	self.textLabel.textColor = [UIColor blackColor];
	self.detailTextLabel.text = nil;
	self.detailTextLabel.textColor = [UIColor grayColor];
	[self setUserInteractionEnabled:YES];
	self.imageView.alpha = 1;
	self.accessoryView = nil;
	self.accessoryType = UITableViewCellAccessoryNone;
    [self.contentView setHidden:NO];
    [_checkmarkProfileImageView removeFromSuperview];
    _checkmarkProfileImageView = nil;
    [self cleanupBackView];
}


- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}


-(void)animateContentViewForPoint:(CGPoint)point velocity:(CGPoint)velocity {
    [super animateContentViewForPoint:point velocity:velocity];
    if (point.x > 0) {
        // set the checkmark's frame to match the contentView
        [self.checkmarkGreyImageView setFrame:CGRectMake(MIN(CGRectGetMinX(self.contentView.frame) - CGRectGetWidth(self.checkmarkGreyImageView.frame), 0), CGRectGetMinY(self.checkmarkGreyImageView.frame), CGRectGetWidth(self.checkmarkGreyImageView.frame), CGRectGetHeight(self.checkmarkGreyImageView.frame))];
        if (point.x >= CGRectGetHeight(self.frame) - 20.) {
            [self.checkmarkGreenImageView setAlpha:1];
        } else {
            [self.checkmarkGreenImageView setAlpha:0];
        }
    } else if (point.x < 0) {
        // set the X's frame to match the contentView
        [self.deleteGreyImageView setFrame:CGRectMake(MAX(CGRectGetMaxX(self.frame) - CGRectGetWidth(self.deleteGreyImageView.frame), CGRectGetMaxX(self.contentView.frame)), CGRectGetMinY(self.deleteGreyImageView.frame), CGRectGetWidth(self.deleteGreyImageView.frame), CGRectGetHeight(self.deleteGreyImageView.frame))];
        if (-point.x >= CGRectGetHeight(self.frame) - 20.) {
            [self.deleteRedImageView setAlpha:1];
        } else {
            [self.deleteRedImageView setAlpha:0];
        }
    }
}


-(void)resetCellFromPoint:(CGPoint)point velocity:(CGPoint)velocity {
    [super resetCellFromPoint:point velocity:velocity];
    if (point.x > 0 && point.x <= CGRectGetHeight(self.frame) - 20.) {
        // user did not swipe far enough, animate the checkmark back with the contentView animation
        [UIView animateWithDuration:self.animationDuration
                         animations:^{
                             [self.checkmarkGreyImageView setFrame:CGRectMake(-CGRectGetWidth(self.checkmarkGreyImageView.frame), CGRectGetMinY(self.checkmarkGreyImageView.frame), CGRectGetWidth(self.checkmarkGreyImageView.frame), CGRectGetHeight(self.checkmarkGreyImageView.frame))];
                         }];
    } else if (point.x < 0) {
        if (-point.x <= CGRectGetHeight(self.frame) - 20.) {
            // user did not swipe far enough, animate the grey X back with the contentView animation
            [UIView animateWithDuration:self.animationDuration
                             animations:^{
                                 [self.deleteGreyImageView setFrame:CGRectMake(CGRectGetMaxX(self.frame), CGRectGetMinY(self.deleteGreyImageView.frame), CGRectGetWidth(self.deleteGreyImageView.frame), CGRectGetHeight(self.deleteGreyImageView.frame))];
                             }];
        } else {
            // user did swipe far enough to meet the delete action requirement, animate the Xs to show selection
            [UIView animateWithDuration:self.animationDuration
                             animations:^{
                                 [self.deleteGreyImageView.layer setTransform:CATransform3DMakeScale(2, 2, 2)];
                                 [self.deleteGreyImageView setAlpha:0];
                                 [self.deleteRedImageView.layer setTransform:CATransform3DMakeScale(2, 2, 2)];
                                 [self.deleteRedImageView setAlpha:0];
                             }];
        }
    }
}

-(void)cleanupBackView {
    [super cleanupBackView];
    [_checkmarkGreyImageView removeFromSuperview];
    _checkmarkGreyImageView = nil;
    [_checkmarkGreenImageView removeFromSuperview];
    _checkmarkGreenImageView = nil;
    [_deleteGreyImageView removeFromSuperview];
    _deleteGreyImageView = nil;
    [_deleteRedImageView removeFromSuperview];
    _deleteRedImageView = nil;
}


-(BOOL)gestureRecognizerShouldBegin:(UIPanGestureRecognizer *)panGestureRecognizer {
    // We only want to deal with the gesture of it's a pan gesture
    if ([panGestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]] && self.revealDirection != RMSwipeTableViewCellRevealDirectionNone && self.shouldDrag) {
        CGPoint translation = [panGestureRecognizer translationInView:[self superview]];
        return (fabs(translation.x) / fabs(translation.y) > 1) ? YES : NO;
    } else {
        return NO;
    }
}


- (void)reserve:(id)sender {
    if ([self.event.has_online_reservation integerValue] > 0) {
        SSWebViewController *reservController = [[SSWebViewController alloc] init];
        [reservController loadURL:[NSURL URLWithString:[@"http://m.dianping.com/reservation/book/getbookingconfig?shopID=" stringByAppendingString:self.event.business_id]]];
        [self.viewController.navigationController pushViewController:reservController animated:YES];
    } else if (self.event.telephone && self.event.telephone.length){
        UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"电话预约" delegate:nil cancelButtonTitle:@"取消" destructiveButtonTitle:self.event.telephone otherButtonTitles:nil];
        actionSheet.actionSheetStyle = UIActionSheetStyleAutomatic;
        [actionSheet showInView:self.viewController.view];
    }
}


@end
